package com.yiwenup.struct._01_linear.list;

import com.yiwenup.struct._01_linear.base.AbstractList;

/**
 * 链表结构：使用虚拟头节点精简，但是不推荐，多了一个不存数据的占内存的
 */
public class SingleLinkedList2<E> extends AbstractList<E> {
    private Node<E> head;

    public SingleLinkedList2() {
        head = new Node<E>(null, null);
    }

    @Override
    public void clear() {
        size = 0;
        head = null;
    }

    @Override
    public E get(int idx) {
        return node(idx).element;
    }

    @Override
    public E set(int idx, E ele) {
        Node<E> node = node(idx);
        E old = node.element;
        node.element = ele;
        return old;
    }

    @Override
    public void insert(int idx, E ele) {
        rangeCheckForAdd(idx);
        Node<E> pre = idx == 0 ? head : node(idx - 1);
        pre.next = new Node<E>(ele, pre.next);
        size++;
    }

    @Override
    public E remove(int idx) {
        rangeCheck(idx);
        Node<E> pre = idx == 0 ? head : node(idx - 1);
        Node<E> node = pre.next;
        pre.next = node.next;
        size--;
        return node.element;
    }

    @Override
    public E remove(E ele) {
        return remove(indexOf(ele));
    }

    @Override
    public int indexOf(E ele) {
        if (ele == null) {
            Node<E> node = head;
            for (int i = 0; i < size; i++) {
                if (node.element == null) {
                    return i;
                }
                node = node.next;
            }
        } else {
            Node<E> node = head;
            for (int i = 0; i < size; i++) {
                if (ele.equals(node.element)) {
                    return i;
                }
                node = node.next;
            }
        }
        return -1;
    }

    /**
     * 获取idx位置的node对象
     *
     * @param idx 索引位置
     * @return node对象
     */
    private Node<E> node(int idx) {
        rangeCheck(idx);

        Node<E> node = this.head.next;

        for (int i = 0; i < idx; i++) {
            node = node.next;
        }

        return node;
    }

    private static class Node<E> {
        private E element;
        private Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }
}
